package ch.fusun.baron.map.ui.views;

import org.eclipse.jface.viewers.ISelection;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.ui.part.ViewPart;

import ch.fusun.baron.map.ui.TileActionRegistry;

/**
 * View for the currently available commands
 */
public class CommandView extends ViewPart {

	/**
	 * ID of the view
	 */
	public static String ID = "ch.fusun.baron.map.ui.views.CommandView"; //$NON-NLS-1$
	private IStructuredSelection selection;

	/**
	 * Injection Constructor
	 */
	public CommandView() {
	}

	@Override
	public void createPartControl(Composite parent) {
		parent.setLayout(new GridLayout(5, false));

		for (final TileAction action : TileActionRegistry.getInstance()
				.getTileActions()) {
			final Button actionButton = new Button(parent, SWT.NONE);
			if (TileActionRegistry.getInstance().hasImage(action)) {
				actionButton.setImage(TileActionRegistry.getInstance()
						.getImage(action, parent.getDisplay()));

			} else {
				actionButton.setText(action.getText());
			}
			actionButton.addSelectionListener(new SelectionAdapter() {
				@Override
				public void widgetSelected(SelectionEvent e) {
					if (selection != null) {
						Object selectedObject = selection.getFirstElement();
						if (selectedObject != null
								&& selectedObject.getClass().equals(
										action.getReactionClass())) {
							action.execute(selectedObject);
						}
					}
				}
			});
		}
	}

	@Override
	public void setFocus() {
		// Do nothing
	}

	/**
	 * Update to new selection
	 * 
	 * @param iSelection
	 *            The new selection
	 */
	public void updateSelection(ISelection iSelection) {
		this.selection = (IStructuredSelection) iSelection;
	}
}
